package com.qf.application.interceprot;

import com.qf.application.commons.exception.UrlException;
import com.qf.application.commons.utils.ServletUtils;
import com.qf.application.context.UserContextHolder;
import com.qf.application.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

@Component
@Slf4j
public class UserUrlInterceptor implements HandlerInterceptor {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("完成权限的校验");

        // 1.获取当前访问的URL
        String curUrl = ServletUtils.getCurrentRequestUrl();

//        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
//            return true;
//        }

        // 2.获取当前登录用户拥有的urls
        LoginUser loginUser = UserContextHolder.get();
        Set<String> permissions = loginUser.getPermissions();

        /// 3、如果当前登录的用户是习惯管理员就不要在验证权限的
        Set<String> roles = loginUser.getRoles();
        if ("admin".equals(loginUser.getUsername())) {
            return true;
        }

        // 3.对比登录用户是否拥有当前url
        Boolean flag = false; // flag决定是否需要放行
        for (String userUrl : permissions) {
            if (antPathMatcher.match(userUrl, curUrl)) {
                flag = true; // 有权限
                break;
            }
        }

        if (!flag) { // 没有权限抛出异常，交给全局异常管理器处理
            throw new UrlException(6001, "您没有权限访问这个资源");
        }
        return flag;
    }

    public static void main(String[] args) {
        AntPathMatcher matcher = new AntPathMatcher();
//        boolean match = matcher.match("/user/remove/*", "/user/remove/10");
//        boolean match = matcher.match("/user/add", "/user/add");
        boolean match = matcher.match("/info/*/*/*", "/info/1/2");
        System.out.println(match);

//        int leve = 1;
//        if (leve == 1) {
//            Thread.sleep(3000);
//        } else if (leve == 2) {
//            Thread.sleep(1000);
//        }else {
//
//        }

    }
}
